import { J_i18n } from './depend';
import { identify, isUndef, checkReg } from '@jiess/utils/packages/tools';
const lan = title => J_i18n(title, title, 'jiess.rule')
/*********************************************
 * 用于element UI的校验规则
 * 在组件中配置rule，传入一个数组
 *********************************************/
//校验是否为数值
export const checkNum = (value) => {
	if (isUndef(value, true)) {
		return false
	} else if (Object.is(Number(value), NaN)) {
		return false
	} else {
		return true
	}
}
const Rules = {
	number: (rule, value, callback) => {
		if (checkNum(value)) {
			callback()
		} else {
			callback(new Error(lan('需要输入数字')))
		}
	},
	integer: (rule, value, callback) => {
		if (checkNum(value)) {
			if (checkReg('integer', value)) {
				callback()
			} else {
				callback(new Error(lan('需要输入正整数')))
			}
		} else {
			callback(new Error(lan('需要输入数字')))
		}
	},
	email: (rule, value, callback) => {
		if (value) {
			if (checkReg('mail', value)) {
				callback()
			} else {
				callback(new Error(lan('输入的邮箱格式不正确')))
			}
		} else {
			callback()
		}
	}
}
// =======================功能区域==============================
export const ruleCheck = {
	required: (data = {}) => {
		return {
			required: true,
			message: data.message || lan('必填'),
			trigger: data.trigger || 'blur'
		}
	},
	integer: () => ({
		validator: Rules.integer,
		trigger: 'blur',
	}),
	number: () => ({
		validator: Rules.number,
		trigger: 'blur',
	}),
	email: () => ({
		validator: Rules.email,
		trigger: 'blur'
	})
}
export default function(rule) {
	return Array.isArray(rule) && rule.map(item => {
		if (identify(item, 'string')) {
			return ruleCheck[item] ? ruleCheck[item]() : {}
		} else if (identify(item, 'object') && item.prop) {
			return ruleCheck[item.prop] ? ruleCheck[item.prop](item) : {}
		} else {
			return item
		}
	})
}
